import {ATTR,TEXT,REPLACE,REMOVE} from './patchTypes'
import { render, setAttrs } from './virtualDom'
import Element from './Element'

let finalPatches = {},
    rnIndex = 0
function doPatch(rDom,patches){
    // console.log(rDom,patches)
    finalPatches = patches
    rNodeWalk(rDom)
      console.log(rDom.childNodes)
}

function rNodeWalk(rNode){
    const rnPatch = finalPatches[rnIndex++],
          chldNode = rNode.childNodes;
    [...chldNode].map((c)=>{
        rNodeWalk(c)
    })
    
    if(rnPatch){
        // console.log(rnPatch)
        patchAction(rNode,rnPatch)
    }
}

function patchAction(rNode,rnPatch){
    // console.log(rNode,rnPatch)
    rnPatch.map((p)=>{
    switch(p.type){
        case ATTR:
            for(let key in p.attrs){
              let value = p.attrs[key]
              if(value){
                setAttrs(rNode,key,value) //更改了属性 调用set
              }else{
                rNode.removeAttribute(key) //没有属性删除该属性
              }
            }
        break;
        case TEXT:
            rNode.textContent = p.text
        break;
        case REPLACE:
         const newNode = (p.newNode instanceof Element) 
                       ? render(p.newNode):
                        document.createTextNode(p.newNode)

                        rNode.parentNode.replaceChild(newNode,rNode)
        break;
        case REMOVE:
            rNode.parentNode.removeChild(rNode)
        break;
        default:
        break;
    }
    })
}


export default doPatch